//
//  XLStatusPictureView.swift
//  SinaProjectTest
//
//  Created by zhanghaifeng on 16/10/28.
//  Copyright © 2016年 BBSWaitting. All rights reserved.
//

import UIKit
import SDWebImage

// 图片间距
private let cellMargin: CGFloat = 5
// 图片宽度图片的高度
private let cellWH = (CGFloat)(Int(XLSCREENW - 20 - cellMargin * 2) / 3)
// cell 的重用标识
private let collectionViewCellID = "collectionViewCellID"

class XLStatusPictureView: UICollectionView {

    // 定义一个属性供外界赋值
    var pictureModel: [XLHomePictureModel]?{
        didSet{
            countLabel.text = "\(pictureModel?.count ?? 0)"
            
//            // 得到配图大小
//            let size = dealScaleSize(count: pictureModel?.count ?? 0)
//            // 更新约束
//            self.snp_updateConstraints { (make) in
//                make.size.equalTo(size)
//            }
            dealScaleSize(count: pictureModel?.count ?? 0)
            // 刷新UI
            reloadData()
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 处理配图的大小
    func dealScaleSize(count: Int){
        // 如果是单张图片
        if count == 1{
            
            // 获取key
            let key = pictureModel?.first?.thumbnail_pic ?? ""
            // 从缓存中获取图片
            let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: key)
            // 因为SDWebImage 下载图片可能因为外界影响导致下载图片不成功 所以说 防止imgae == nil 我们做判断
            if image != nil{
                self.snp_updateConstraints(closure: { (make) in
                    make.size.equalTo(image!.size)
                })
                layoutIfNeeded()
                // 设置itemSize
                let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = image!.size
                
                return
            }
            
        }
        
        // 行数 列数
        let col = count >= 3 ? 3 : count
        let row = (count - 1) / 3 + 1
        
        // 最终的宽和高
        let W = CGFloat(col) * cellWH + CGFloat(col - 1) * cellMargin
        let H = CGFloat(row) * cellWH + CGFloat(row - 1) * cellMargin
        
        self.snp_updateConstraints(closure: { (make) in
            make.size.equalTo(CGSize(width: W, height: H))
        })
        layoutIfNeeded()
        // 设置itemSize
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        
    }
    
    
    // 创建视图
    private func setupUI(){
//        backgroundColor = XLRandomColor()
        
        // 得到layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        // 设置 itemSize
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        // 设置cell 的间距
        layout.minimumLineSpacing = cellMargin
        layout.minimumInteritemSpacing = cellMargin
        // 设置代理 数据源
        dataSource = self
        // 注册cell
        register(XLStatusPictureViewCell.self, forCellWithReuseIdentifier: collectionViewCellID)
//         添加控件
//        addSubview(countLabel)
////         添加约束
//        countLabel.snp_makeConstraints { (make) in
//            make.center.equalTo(self)
//        }
        
    }
    
    // 懒加载 控件
    lazy var countLabel: UILabel = {
        let countLab = UILabel(text: "9", fontSize: 35, textColor: UIColor.red)
        countLab.textAlignment = .center
        return countLab
    }()

}

//MARK: - UICollectionViewDataSource
extension XLStatusPictureView: UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureModel?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellID, for: indexPath) as! XLStatusPictureViewCell
//        cell.backgroundColor = XLRandomColor()
        // 赋值
        cell.picUrl = pictureModel![indexPath.item]
        return cell
    }
    
}

// 自定义配图的cell
class XLStatusPictureViewCell: UICollectionViewCell{
    
    // 定义属性 供外界使用数据
    var picUrl: XLHomePictureModel?{
        didSet{
                // 赋值
                bgImageV.xl_setImage(withUrlString: picUrl?.thumbnail_pic, placeholderImgName: "timeline_image_placeholder")
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 设置视图
    func setupUI(){
        // 加载控件
        contentView.addSubview(bgImageV)
        // 添加约束
        bgImageV.snp_updateConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
    }
    
    // 懒加载控件
    private lazy var bgImageV: UIImageView = {
        let image = UIImageView(imgNamed: "timeline_image_placeholder")
        // 图片显示样式
        image.contentMode = .scaleAspectFill
        image.layer.masksToBounds = true
        return image
    }()

    
}

